package likou;

/**
 * @description: 给你一个字符串 columnTitle ，表示 Excel 表格中的列名称。返回该列名称对应的列序号。
 * @title: titleToNumberDemo
 * @author: zp
 * @date: 2021/12/2 20:31
 */
public class TitleToNumberDemo {
    public static void main(String[] args) {
        System.out.println(titleToNumber("ZSKCKWSO"));
    }

    /**
     * @description: Excel行号转对应数字
     * @author: zp
     * @date: 2021/12/2 21:10
     * @param: columnTitle
     * @return: int
     */
    public static int titleToNumber(String columnTitle) {
        if (columnTitle == null || columnTitle.length() < 1) {
            return 0;
        }
        int number = 0;
        int multiple = 1;
        for (int i = columnTitle.length() - 1; i >= 0; i--) {
            int k = columnTitle.charAt(i) - 'A' + 1;
            number += k * multiple;
            multiple *= 26;
        }
        return number;

    }

    /**
     * @description: 数字转Excel的对应行号
     * @author: zp
     * @date: 2021/12/2 21:10
     * @param: num
     * @return: java.lang.String
     */
    public static String numberToTitle(int num) {
        if (num < 0) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        while (num > 0) {
            num--;
            stringBuilder.append((char) (num % 26 + 'A'));
            num /= 26;
        }
        return stringBuilder.reverse().toString();
    }
}
